<template>
  <div class="star-rating">
    <div class="star-container">
      <!-- 完整星星 -->
      <div class="stars-full" :style="{ width: fullStarsWidth + '%', color: filledColor }">
        <el-icon v-for="n in 5" :key="`full-${n}`" class="star-icon"
          ><StarFilled
        /></el-icon>
      </div>
      <!-- 背景星星 -->
      <div class="stars-bg" :style="{ color: backgroundStarColor }">
        <el-icon v-for="n in 5" :key="`bg-${n}`" class="star-icon"
          ><Star
        /></el-icon>
      </div>
    </div>
    <!-- 显示评分数值 -->
    <span v-if="showScore" class="score" :style="{ color: filledColor }">{{ formattedScore }}</span>
  </div>
</template>

<script>
import { computed, defineComponent } from "vue";
// 从 @element-plus/icons-vue 导入 StarFilled
import { Star, StarFilled } from "@element-plus/icons-vue";

export default defineComponent({
  name: "StarRating",
  // 在组件中注册 StarFilled
  components: { StarFilled },
  props: {
    score: {
      type: Number,
      default: 0,
      required: true,
    },
    showScore: {
      type: Boolean,
      default: true,
    },
    precision: {
      type: Number,
      default: 1,
    },
    emptyColor: {
      type: String,
      default: "#c0c4cc", // 默认的空星星颜色
    },
    filledColor: {
      type: String,
      default: "#FFA000", // 默认的填充星星颜色 (例如，深黄色/琥珀色)
    },
  },
  setup(props) {
    // 计算完整星星的宽度百分比
    const fullStarsWidth = computed(() => {
      // 确保评分在0-5之间
      const validScore = Math.min(5, Math.max(0, props.score));
      // 根据分数的整数部分计算实心星星的数量
      const numFullStars = Math.floor(validScore);
      // 转换为百分比 (0-100)
      return (numFullStars / 5) * 100;
    });

    // 格式化评分显示
    const formattedScore = computed(() => {
      return props.score.toFixed(props.precision);
    });

    // 背景星星的颜色始终是 emptyColor
    const backgroundStarColor = computed(() => {
      return props.emptyColor;
    });

    return {
      fullStarsWidth,
      formattedScore,
      backgroundStarColor,
    };
  },
});
</script>

<style scoped>
.star-rating {
  display: inline-flex;
  align-items: center;
}

.star-container {
  position: relative;
  display: inline-block;
}

.stars-bg {
  display: inline-block;
  color: var(--text-color-secondary); /* 使用次要文本颜色，确保可见 */
}

.stars-full {
  position: absolute;
  top: 0;
  left: 0;
  white-space: nowrap;
  overflow: hidden;
  /* color: var(--accent-color); 已被内联样式取代 */
}

.star-icon {
  font-size: 18px;
  margin-right: 2px;
  color: inherit !important; /* 强制继承父元素的颜色 */
}

.score {
  margin-left: 8px;
  font-size: 14px;
  /* color: var(--accent-color); 已被内联样式取代 */
}
</style>
